﻿/* 2013/6/10 */
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Cosmos.IO.FileSystemPath.Searcher
{
    /// <summary>
    /// Generates paths by specifying search condition.
    /// Searches file or directory by checking substrings of its name.
    /// 
    /// File name which contains any one of the substrings in search
    /// pattern will be returned.
    /// If search pattern is null or empty, all paths will
    /// be returned.
    /// </summary>
    public class SubstringFilePathSearcher : FileSystemInfoPathSearcher
    {
        /// <summary>
        /// The separators of substrings in search pattern.
        /// </summary>
        protected string[] separators = new string[] { " " };

        protected string[] substrings = null;

        protected override void Prepare(string searchPattern)
        {
            substrings = searchPattern.Split(separators,
                StringSplitOptions.RemoveEmptyEntries);
        }

        protected override bool Match(FileSystemInfo info)
        {
            string name = info.Name;
            if (name != null)
            {
                if (substrings == null || substrings.Length == 0)
                {
                    return true;
                }

                foreach (string aSubstring in substrings)
                {
                    if (name.Contains(aSubstring))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// Gets or sets the separators of substrings in search pattern.
        /// Default value is space only.
        /// </summary>
        public string[] Separators
        {
            get { return separators; }
            set { separators = value; }
        }
    }
}
